# coding: utf-8
from PyQt6.QtCore import Qt
from PyQt6.QtWidgets import QHBoxLayout
from qfluentwidgets import PrimaryPushButton, FluentIcon as FIF, ComboBox, BodyLabel, InfoBar

from common import SingleIcon, PILFormat, ImageConverter
from components import BaseScrollArea, DragDropButton, FileGroupCardWidget, FolderLineEdit


class PictureConversionView(BaseScrollArea):
    title = '图片格式转换'
    description = '将图片转换为其他格式，如JPG、PNG、BMP等。'
    object_name = 'PictureConversionView'
    icon = SingleIcon.CONVERSION

    def __init__(self, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout()
        self.dragDropButton = DragDropButton(self)
        self.groupHeaderCardWidget = FileGroupCardWidget('图片列表', self)
        self.typeComboBox = ComboBox(self)
        self.saveLineEdit = FolderLineEdit(self)
        self.startBtn = PrimaryPushButton(FIF.PLAY, '开始转换', self)
        self.__initWidgets()
        self.__connectSignals()

    def __initWidgets(self):
        self.setReturnVisible(True)
        self.dragDropButton.setFixedHeight(200)
        self.dragDropButton.setFilter(PILFormat.__args__)
        self.typeComboBox.setFixedWidth(80)
        self.typeComboBox.addItems(PILFormat.__args__)
        self.saveLineEdit.setPlaceholderText('请选择保存路径')

        self.scrollLayout.addWidget(self.dragDropButton)
        self.scrollLayout.addWidget(self.groupHeaderCardWidget)

        self.horizontalLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(BodyLabel('格式：', self))
        self.horizontalLayout.addWidget(self.typeComboBox, 1)
        self.horizontalLayout.addWidget(self.saveLineEdit, 1)
        self.horizontalLayout.addWidget(self.startBtn, 1)

        self.scrollLayout.addLayout(self.horizontalLayout)

    def __connectSignals(self):
        self.dragDropButton.fileChanged.connect(self.onFileChanged)
        self.startBtn.clicked.connect(self.onStarted)

    def onFileChanged(self, file: str):
        if file in self.groupHeaderCardWidget.files:
            return
        self.groupHeaderCardWidget.addFile(file)

    def onStarted(self):
        files = self.groupHeaderCardWidget.files
        save_path = self.saveLineEdit.text()
        format = self.typeComboBox.currentText()
        if not files or not save_path or not format:
            InfoBar.warning('', '请选择文件、保存路径和格式', duration=2000, parent=self)
            return
        self.load(ImageConverter.pool_convert, files, save_path, format)
